#include "GameObject.h"
#include "CRender.h"
#include "CLight.h"
#include "CMesh.h"
#include "CPosition.h"
#include "COrientation.h"
#include "GameSceneManager.h"
#include "GameObjectManager.h"
#include "GameSystemManager.h"

comp_id_type CRender::mFamilyID = "CRender";
comp_id_type CRender::mComponentID = "CRender";

comp_id_type CRenderTemplate::mFamilyID = "CRender";
comp_id_type CRenderTemplate::mComponentID = "CRender";

CRenderTemplate::CRenderTemplate() {

}
CRenderTemplate::~CRenderTemplate() {

}
GameComponent *CRenderTemplate::makeComponent() {
	CRender *comp = new CRender(this);
	return comp;
}

CRender::CRender()
{

}
CRender::CRender(CRenderTemplate *templ)
{
	
}
CRender::~CRender()
{
	mNode->detachAllObjects(); // _deinitialise();
	delete mNode;
}
void CRender::setup() {
	CPosition *mCPosition = dynamic_cast<CPosition*>(getOwnerObject()->getComponent("CPosition"));
	COrientation *mCOrientation = dynamic_cast<COrientation*>(getOwnerObject()->getComponent("COrientation"));
	CMesh *mCMesh = dynamic_cast<CMesh*>(getOwnerObject()->getComponent("CMesh"));
	CLight *mCLight = dynamic_cast<CLight*>(getOwnerObject()->getComponent("CLight"));

	std::string name;
	name = "CRenderNode" + StringConverter::toString(GameObjectManager::getSingleton()->getNextCompIndex());

	mNode = GameSceneManager::getSingleton()->getSceneManager()->getRootSceneNode()->createChildSceneNode(); //name

	if(mCMesh)
		mNode->attachObject(mCMesh->mEntity);

	if(mCLight) {
		mNode->attachObject(mCLight->mLight);
		
		//std::string name;
		//name = "CMeshComponent" + StringConverter::toString(GameObjectManager::getSingleton()->getNextCompIndex());
		//mCMesh->mEntity = GameSceneManager::getSingleton()->getSceneManager()->createEntity(name,"arrow.mesh");

	}

	if(mCPosition)
		mNode->setPosition(mCPosition->Position);
	if(mCOrientation)
		mNode->setOrientation(mCOrientation->Orientation);

}
void CRender::update() {
	std::string owner_id = getOwnerObject()->getID();

	if(owner_id == gom_config.objectInHand) {
		Ogre::Vector3 v = GameSystemManager::getSingleton()->getTerrain()->rayIntersectsTerrain();
		//Ogre::Vector3 v = GameSystemManager::getSingleton()->getTerrain()->rayIntersectsTerrain();	
		mNode->setPosition(v);

	}
}

